package com.peng.community.controller;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.Event;
import com.peng.community.event.EventProducer;
import com.peng.community.util.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class ShareController implements CommunityConstant {
    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;

    @GetMapping("/share")
    @ResponseBody
    public String share(String htmlUrl) {

        String fileName = CommunityUtils.getUUID();

        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("fileName", fileName)
                .setData("htmlUrl", htmlUrl)
                .setData("suffix",".png");
        eventProducer.send(event);

        Map<String, Object> map = new HashMap<>();

        //文件系统的图片无法直接访问，需要通过请求响应字节流
        map.put("shareUrl", domain + contextPath + "/share/img/" + fileName);

        //七牛云图片路径。
//        map.put("shareUrl", shareBucketUrl + "/" + fileName);
        return CommunityUtils.toJsonString(0,null,map);
    }


    @GetMapping("/share/img/{filename}")
    public void getShareImg(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (StringUtils.isBlank(filename)) {
            throw new IllegalArgumentException("文件名不能空");
        }
        String imgPath = wkImageStorage + "/" + filename + ".png";
        try {
            ServletOutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(imgPath));

            byte[] bytes = new byte[1024];
            int b;
            while ((b = fis.read(bytes)) != -1) {
                //==-1表示这次没有读取到值
                //b表示读取到缓冲区中有效字符的长度
                os.write(bytes,0,b);
            }
        } catch (IOException e) {
            log.error("获取长图失败：{}", e.getCause().toString());
            e.printStackTrace();
        }


    }

}
